package cn.appsys.controller;

import cn.appsys.pojo.*;
import cn.appsys.service.category.CategoryService;
import cn.appsys.service.dictionary.DictionaryService;
import cn.appsys.service.info.InfoService;
import cn.appsys.service.version.VersionService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/appInfo")
public class AppInfoController {
    @Resource
    private InfoService infoService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private VersionService versionService;

    @RequestMapping(value = "/list")
    public String getList(Model model, HttpSession session,
                          @RequestParam(value = "_softwareName", required = false) String _softwareName,
                          @RequestParam(value = "_status", required = false) String _status,
                          @RequestParam(value = "_flatformId", required = false) String _flatformId,
                          @RequestParam(value = "_categoryLevel1", required = false) String _categoryLevel1,
                          @RequestParam(value = "_categoryLevel2", required = false) String _categoryLevel2,
                          @RequestParam(value = "_categoryLevel3", required = false) String _categoryLevel3,
                          @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        Integer devId = ((DevUser) session.getAttribute(Constants.USER_SESSION)).getId();
        List<Info> infoList = null;
        List<Dictionary> statusList = null;
        List<Dictionary> flatformList = null;
        //三级分类
        List<Category> categoryLevel1List = null;
        List<Category> categoryLevel2List = null;
        List<Category> categoryLevel3List = null;
        //分页数据
        int pageSize = Constants.pageSize;
        Integer currentPageNo = 1;
        Integer status = null;
        Integer categoryLevel1 = null;
        Integer categoryLevel2 = null;
        Integer categoryLevel3 = null;
        Integer flatformId = null;

        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        if (_status != null && !_status.equals("")) {
            status = Integer.valueOf(_status);
        }
        if (_categoryLevel1 != null && !_categoryLevel1.equals("")) {
            categoryLevel1 = Integer.valueOf(_categoryLevel1);
        }
        if (_categoryLevel2 != null && !_categoryLevel2.equals("")) {
            categoryLevel2 = Integer.valueOf(_categoryLevel2);
        }
        if (_categoryLevel3 != null && !_categoryLevel3.equals("")) {
            categoryLevel3 = Integer.valueOf(_categoryLevel3);
        }
        if (_flatformId != null && !_flatformId.equals("")) {
            flatformId = Integer.valueOf(_flatformId);
        }

        int totalCount = 0;
        totalCount = infoService.findAppInfoCount(_softwareName, status, flatformId,
                categoryLevel1, categoryLevel2, categoryLevel3, devId);
        PageSupport page = new PageSupport();
        page.setCurrentPageNo(currentPageNo);
        page.setPageSize(pageSize);
        page.setTotalCount(totalCount);
        page.setTotalPageCount(totalCount % pageSize == 0 ?
                (totalCount / pageSize) : (totalCount / pageSize + 1));
        //获取集合
        infoList = infoService.findAppInfoList(_softwareName, status, flatformId,
                categoryLevel1, categoryLevel2, categoryLevel3,
                devId, (page.getCurrentPageNo() - 1) * page.getPageSize()
                , page.getPageSize());

        System.out.println("infoList==========================" + infoList.size());
        statusList = this.getDictionaryList("APP_STATUS");
        flatformList = this.getDictionaryList("APP_FLATFORM");
        //一级分类
        categoryLevel1List = categoryService.getCategoryList(null);

        model.addAttribute("appInfolist", infoList);
        model.addAttribute("statusList", statusList);
        model.addAttribute("flatformList", flatformList);
        model.addAttribute("categoryLevel1List", categoryLevel1List);
        model.addAttribute("categoryLevel2List", categoryLevel2List);
        model.addAttribute("categoryLevel3List", categoryLevel3List);
        model.addAttribute("pages", page);
        model.addAttribute("status", status);
        model.addAttribute("softwareName", _softwareName);
        model.addAttribute("categoryLevel1", categoryLevel1);
        model.addAttribute("categoryLevel2", categoryLevel2);
        model.addAttribute("categoryLevel3", categoryLevel3);
        model.addAttribute("flatformId", flatformId);
        System.out.println("statusList====" + statusList.size());
        System.out.println("categorylevel1List====" + categoryLevel1List.size());
        System.out.println("faltformList====" + flatformList.size());

        return "developer/appinfolist";
    }

    public List<Dictionary> getDictionaryList(String typeCode) {
        return dictionaryService.findDictionaryList(typeCode);
    }

    /**
     * 根据parentId查询二三级
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/categorylevellist.json", method = RequestMethod.GET)
    @ResponseBody
    public List<Category> getAppCategoryList(@RequestParam String pid) {
        if (pid.equals("")) {
            pid = null;
        }
        return getCategoryList(pid);
    }

    private List<Category> getCategoryList(String pid) {
        List<Category> categoryList = null;
        categoryList = categoryService.getCategoryList(pid == null ? null : Integer.parseInt(pid));
        System.out.println("category=====================" + categoryList.size());
        return categoryList;
    }

    @RequestMapping(value = "/datadictionarylist.json", method = RequestMethod.GET)
    @ResponseBody
    public List<Dictionary> getDataDictionaryList(@RequestParam String tcode) {
        return this.getDictionaryList(tcode);
    }


    @RequestMapping(value = "/apkexist.json", method = RequestMethod.GET)
    @ResponseBody
    public Object apkNameExits(@RequestParam String APKName) {
        HashMap<String, String> hashMap = new HashMap<>();
        if (StringUtils.isEmpty(APKName)) {
            hashMap.put("APKName", "empty");
        } else {
            Info info = null;
            info = infoService.findAppInfo(null, APKName);
            if (info != null) {
                hashMap.put("APKName", "exist");
            } else {
                hashMap.put("APKName", "noexist");
            }
        }
        return hashMap;
    }

    @RequestMapping(value = "/appinfoadd", method = RequestMethod.GET)
    public String appinfoadd(@ModelAttribute("info") Info info) {
        return "developer/appinfoadd";
    }


    @RequestMapping(value = "/appinfoaddsave", method = RequestMethod.POST)
    public String addSave(Info info, HttpSession session, HttpServletRequest request
            , @RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach) {
        String logoPicPath = null;
        String logoLocPath = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + java.io.File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            int fileSize = 500000;
            if (attach.getSize() > fileSize) {
                request.setAttribute("fileUpLoadError", Constants.FILEUPLOAD_ERROR_4);
                return "developer/appinfoadd";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")) {
                String fileName = info.getAPKName() + ".jpg";
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("fileUpLoadError", Constants.FILEUPLOAD_ERROR_2);
                    return "developer/appinfoadd";
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            }

        } else {
            request.setAttribute("fileUpLoadError", Constants.FILEUPLOAD_ERROR_3);
            return "developer/appinfoadd";
        }
        info.setCreatedBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
        info.setCreationDate(new Date());
        info.setLogoPicPath(logoPicPath);
        info.setLogoLocPath(logoLocPath);
        info.setDevId(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
        info.setStatus(1);
        if (infoService.add(info)) {
            return "redirect:/appInfo/list";
        }
        return "developer/appinfoadd";
    }

    @RequestMapping(value = "/appinfomodify", method = RequestMethod.GET)
    public String modifyInfo(@RequestParam("id") String id,
                             @RequestParam(value = "error", required = false) String fileUploadError,
                             Model model) {
        if (fileUploadError != null && ("error2").equals(fileUploadError)) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_2;
        } else if (fileUploadError != null && ("error4").equals(fileUploadError)) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_4;
        } else if (fileUploadError != null && ("error3").equals(fileUploadError)) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_3;
        }
        Info info = null;
        info = infoService.findAppInfo(Integer.parseInt(id), null);
        model.addAttribute(info);
        model.addAttribute("fileUploadError", fileUploadError);
        return "developer/modifyappinfo";
    }

    @RequestMapping(value = "/delfile.json", method = RequestMethod.GET)
    @ResponseBody
    public Object delFile(@RequestParam(value = "id", required = false) String id,
                          @RequestParam(value = "flag", required = false) String flag) {
        HashMap<String, String> hashMap = new HashMap<>();
        String filePath = null;
        if (id == null || id.equals("") || flag == null || flag.equals("")) {
            hashMap.put("result", "failed");
        } else if (flag.equals("logo")) {
            filePath = infoService.findAppInfo(Integer.parseInt(id), null).getLogoLocPath();
            File file = new File(filePath);
            if (file.exists()) {
                if (file.delete()) {
                    if (infoService.delAppLog(Integer.parseInt(id))) {
                        hashMap.put("result", "success");
                    }
                }
            }
        } else if (flag.equals("apk")) {
            filePath = (versionService.getVersionById(Integer.parseInt(id))).getApkLocPath();
            File file = new File(filePath);
            if (file.exists()) {
                if (file.delete()) {
                    if (versionService.delVersionAPK(Integer.parseInt(id))) {
                        hashMap.put("result", "success");
                    }
                }
            }
        }
        return hashMap;
    }

    @RequestMapping(value = "/appinfomodifysave", method = RequestMethod.POST)
    public String appInfoModifySave(Info info, HttpSession session, HttpServletRequest request,
                                    @RequestParam(value = "attach", required = false) MultipartFile attach) {
        String logoPicPath = null;
        String logoLocPath = null;
        String APKName = info.getAPKName();
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + java.io.File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            int fileSize = 500000;
            if (attach.getSize() > fileSize) {
                return "redirect:/appInfo/appinfomodify?id=" + info.getId() + "&error=error4";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")) {
                String fileName = info.getAPKName() + ".jpg";
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    return "redirect:/appInfo/appinfomodify?id=" + info.getId() + "&error=error2";
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            }

        }
        info.setModifyBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
        info.setModifyDate(new Date());
        info.setLogoPicPath(logoPicPath);
        info.setLogoLocPath(logoLocPath);
        if (infoService.modify(info)) {
            return "redirect:/appInfo/list";
        }
        return "developer/appinfomodify";
    }

    @RequestMapping(value = "/appversionadd")
    public String addVersion(@RequestParam("id") String id,
                             @RequestParam(value = "error", required = false) String fileUploadError,
                             Version version,
                             Model model) {
        if (null != fileUploadError && !fileUploadError.equals("error1")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_1;
        } else if (null != fileUploadError && !fileUploadError.equals("error2")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_2;
        } else if (null != fileUploadError && !fileUploadError.equals("error3")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_3;
        }
        version.setAppId(Integer.parseInt(id));
        List<Version> versionList = null;
        versionList = versionService.getVersionList(Integer.parseInt(id));
        model.addAttribute("appVersionList", versionList);
        model.addAttribute("fileUpLoadError", fileUploadError);
        model.addAttribute(version);
        return "developer/appversionadd";
    }

    @RequestMapping(value = "/addversionsave", method = RequestMethod.POST)
    public String addVersionSave(Version version, HttpSession session,
                                 HttpServletRequest request,
                                 @RequestParam(value = "a_downLoadLink", required = false) MultipartFile attach) {
        String downLoadLink = null;
        String apkLocPath = null;
        String apkFileName = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")) {
                String apkName = null;
                apkName = infoService.findAppInfo(version.getAppId(), null).getAPKName();
                if (apkName == null || apkName.equals("")) {
                    return "redirect:/appInfo/appversionadd?id=" + version.getAppId() + "&error=error1";
                }
                apkFileName = apkName + "-" + version.getVersionNo() + ".apk";
                File targetFile = new File(path, apkFileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    return "redirect:/appInfo/appversionadd?id=" + version.getAppId() + "&error=error2";
                }
                downLoadLink = request.getContextPath() + "/statics/uploadfiles/" + apkFileName;
                apkLocPath = path + File.separator + apkFileName;
            } else {
                return "redirect:/appInfo/appversionadd?id=" + version.getAppId() + "&error=error3";
            }
        }
        version.setCreatedBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
        version.setCreationDate(new Date());
        version.setDownloadLink(downLoadLink);
        version.setApkLocPath(apkLocPath);
        version.setApkFileName(apkFileName);
        if (versionService.appVersionSave(version)) {
            return "redirect:/appInfo/list";
        }
        return "redirect:/appInfo/appversionadd?id=" + version.getAppId();
    }


    @RequestMapping(value = "/appversionmodify")
    public String VersionModify(@RequestParam("aid") String aid,
                                @RequestParam("vid") String vid,
                                @RequestParam(value = "error", required = false) String fileUploadError,
                                Model model) {
        Version version = null;
        List<Version> versionList = null;
        if (fileUploadError != null && fileUploadError.equals("error1")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_1;
        } else if (fileUploadError != null && fileUploadError.equals("error2")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_2;
        } else if (fileUploadError != null && fileUploadError.equals("error3")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_3;
        } else if (fileUploadError != null && fileUploadError.equals("error4")) {
            fileUploadError = Constants.FILEUPLOAD_ERROR_4;
        }
        version = versionService.getVersionById(Integer.parseInt(vid));
        versionList = versionService.getVersionList(Integer.parseInt(aid));
        model.addAttribute(version);
        model.addAttribute("versionList", versionList);
        model.addAttribute("fileUploadError", fileUploadError);
        return "developer/appversionmodify";
    }

    @RequestMapping(value = "/appversionmodifysave", method = RequestMethod.POST)
    public String midifyVersionSave(Version version, HttpSession session, HttpServletRequest request,
                                    @RequestParam(value = "attach", required = false) MultipartFile attach) {
        String downLoadLink = null;
        String apkLocPath = null;
        String apkFileName = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")) {
                String apkName = null;
                apkName = infoService.findAppInfo(version.getAppId(), null).getAPKName();
                if (apkName == null || apkName.equals("")) {
                    return "redirect:/appInfo/appversionadd?id=" + version.getAppId() + "&error=error1";
                }
                apkFileName = apkName + "-" + version.getVersionNo() + ".apk";
                File targetFile = new File(path, apkFileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    return "redirect:/appInfo/appversionadd?id=" + version.getAppId() + "&error=error2";
                }
                downLoadLink = request.getContextPath() + "/statics/uploadfiles/" + apkFileName;
                apkLocPath = path + File.separator + apkFileName;
            } else {
                return "redirect:/appInfo/appversionadd?id=" + version.getAppId() + "&error=error3";
            }
        }
        version.setModifyBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
        version.setModifyDate(new Date());
        version.setDownloadLink(downLoadLink);
        version.setApkLocPath(apkLocPath);
        version.setApkFileName(apkFileName);
        if (versionService.updateVersion(version)) {
            return "redirect:/appInfo/list";
        }
        System.out.println("修改版本信息失败");

        return "developer/appversionmodify";
    }


    @RequestMapping(value = "/appview/{id}", method = RequestMethod.GET)
    public String view(@PathVariable String id, Model model) {
        Info info = null;
        List<Version> versionList = null;
        info = infoService.findAppInfo(Integer.parseInt(id), null);
        versionList = versionService.getVersionList(Integer.parseInt(id));
        model.addAttribute("appVersionList", versionList);
        model.addAttribute(info);
        return "developer/appinfoview";
    }

    @RequestMapping(value = "/delapp.json", method = RequestMethod.GET)
    @ResponseBody
    public Object delAPP(@RequestParam(value = "id") String id) {
        HashMap<String, String> hashMap = new HashMap<>();
        if (StringUtils.isEmpty(id)) {
            hashMap.put("delResult", "notexist");
        } else if (infoService.removeApp(Integer.parseInt(id))) {
            hashMap.put("delResult", "true");
        } else {
            hashMap.put("delResult", "false");
        }
        return hashMap;
    }
    @RequestMapping(value = "/{appId}/sale",method = RequestMethod.PUT)
    @ResponseBody
    public Object sale(@PathVariable String appId,HttpSession session){
        HashMap<String, Object> hashMap = new HashMap<>();
        Integer appIdInteger=0;
        appIdInteger=Integer.parseInt(appId);
        hashMap.put("errorCode","0");
        if(appIdInteger>0){
            DevUser devUser= ((DevUser)session.getAttribute(Constants.USER_SESSION));
            Info info=new Info();
            info.setModifyBy(devUser.getId());
            info.setId(appIdInteger);
            if(infoService.appsysUpdateSaleStatusByAppId(info)){
                hashMap.put("resultMsg","success");
            }else{
                hashMap.put("resultMsg","failed");
            }
        }else{
            hashMap.put("errorCode","param000001");
        }
        return hashMap;

    }

}
